import "./render"; // 初始化Canvas
import BackGround from "./runtime/background"; // 导入背景类
import Slot from "./runtime/slot"; // 导入背景类
import Cards from "./runtime/cards"; // 导入背景类
import Grid from "./runtime/grid"; // 导入背景类
import { SCREEN_HEIGHT, SCREEN_WIDTH } from "./render";
import DataBus from "./databus"; // 导入数据类，用于管理游戏状态和数据
import Player from "./player/index"; // 导入玩家类
import GameInfo from "./runtime/gameinfo";
import Music from './runtime/music'; // 导入音乐类

const ctx = canvas.getContext("2d"); // 获取canvas的2D绘图上下文;

GameGlobal.databus = new DataBus(); // 全局数据管理，用于管理游戏状态和数据
GameGlobal.musicManager = new Music(); // 全局音乐管理实例
// wx.loadFont("https://at.alicdn.com/t/c/font_1634113_rg6ld8wp8l.ttf")
// wx.loadFont("font/iconfont.ttf")

/**
 * 游戏主函数
 */
export default class Main {
  aniId = 0; // 用于存储动画帧的ID
  bg = new BackGround(); // 创建背景
  grid = new Grid(); // 创建网格
  slot = new Slot(); // 创建卡槽
  cards = new Cards(); // 创建卡片

  player = new Player();
  gameInfo = new GameInfo(); // 创建游戏UI显示

  debugger = false;

  constructor() {
    const bgAllImagePromise = this.bg.loadAllImagePromise();
    const slotAllImagePromise = this.slot.loadAllImagePromise();
    const cardsAllImagePromise = this.cards.loadAllImagePromise();
    Promise.all([
      bgAllImagePromise,
      slotAllImagePromise,
      ...cardsAllImagePromise,
    ]).then(() => {
      console.log("所有图片加载完成");
      // 开始游戏
      this.start();
    });

    // 当开始游戏被点击时，重新开始游戏
    // this.gameInfo.on("restart", this.start.bind(this));
    this.gameInfo.on("replay", this.replay.bind(this));
    this.gameInfo.on("revoke", this.revoke.bind(this));
    this.gameInfo.on("music", this.music.bind(this));
    this.player.on("clcikCard", this.clcikCard.bind(this));

    
  }

  /**
   * 开始或重启游戏
   */
  start() {
    GameGlobal.databus.reset(); // 重置数据
    this.render(); // 渲染游戏画面

    
  }
  // 游戏逻辑更新主函数
  update() {
    /* if (GameGlobal.databus.isGameOver) {
      return;
    } */

    /* // const canvas = wx.createCanvas();
    // const ctx = canvas.getContext("2d"); // 获取canvas的2D绘图上下文;
 */
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布

    this.bg.update(ctx); // 更新背景
    this.debugger && this.grid.render(ctx); // 绘制网格

    this.cards.render(ctx, GameGlobal.databus.cardsData);

    this.slot.update(ctx);
    this.gameInfo.render(ctx);
    /* const hideImg = canvas.toDataURL("image/png", 1);

    // setTimeout(() => {
      ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
      // 绘制第一张背景
      ctx.drawImage(canvas, 0, 0);
    // }, 300); */



    
  }

  createData(level) {
    const { arr } = this.grid.createData(level);
    //分组 分配图案
    const patternList = this.cards.randomPicArr(arr);
    arr.map((item, i) => Object.assign(item, { picIndex: patternList[i] }));

    return arr;
  }
  render() {
    ctx.restore();
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布

    this.bg.render(ctx);
    this.debugger && this.grid.render(ctx); // 绘制网格

    this.slot.render(ctx); // 绘制卡槽
    console.log(GameGlobal.databus.GameIndex);
    const arr = this.createData(GameGlobal.databus.GameIndex);
    GameGlobal.databus.cardsData = arr;

    this.gameInfo.render(ctx);

   

    this.cards.render(ctx, arr);

    
  }

  clcikCard(info) {
    if (!info) {
      console.log("点击到了空白处");
      return;
    }

    const { cardData: selectedItem, index: selectedIndex } = info;

    if (selectedItem.disabled) {
      return;
    }

    GameGlobal.musicManager.playClick();

    GameGlobal.databus.slotCardsdData.push(selectedItem);
    GameGlobal.databus.selectedData.push(selectedItem);
    GameGlobal.databus.cardsData.splice(selectedIndex, 1);
    this.update();
    if (GameGlobal.databus.slotCardsdData.length >= 7) {
      /* wx.showModal({
        title: "闯关失败",
        content: "非常可惜，请再次挑战",
      }); */
      GameGlobal.databus.gameOver();
      GameGlobal.musicManager.playLose();
      wx.showModal({
        title: "游戏结束",
        content: "请重新开始",
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            this.start();
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    } else if (
      GameGlobal.databus.cardsData.length === 0 &&
      GameGlobal.databus.slotCardsdData.length === 0
    ) {
      GameGlobal.musicManager.playWin();
      wx.showModal({
        title: "闯关成功",
        content: "恭喜您，即将进入下一关",
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            GameGlobal.databus.GameIndex++;
            wx.setStorageSync("GameIndex", GameGlobal.databus.GameIndex);
            this.render();
          }
        },
      });
      // GameGlobal.databus.gameOver();
    }
  }
  replay() {
    // 重玩逻辑
    if (!GameGlobal.databus.selectedData.length) {
      wx.showModal({
        title: "提示",
        content: "已经还原当前关卡，请开始游戏",
      });
      return;
    }

    while (GameGlobal.databus.selectedData.length) {
      const popItem = GameGlobal.databus.selectedData.pop();
      GameGlobal.databus.cardsData.splice(popItem.index, 0, popItem);
    }

    GameGlobal.databus.slotCardsdData = [];

    this.update();
  }
  music(status){
    if (status=='on'){
      this.gameInfo.drawMusicOffButton(ctx);
      GameGlobal.musicManager.stopAll();
    }else{
      this.gameInfo.drawMusicOnButton(ctx);
      GameGlobal.musicManager.playAll();
    } 
    console.log(status);
  }
  revoke() {
    // 撤回逻辑
    if (!GameGlobal.databus.selectedData.length) {
      wx.showModal({
        title: "提示",
        content: "已经撤回到第一步了，请开始游戏",
      });
      return;
    }

    const popItem = GameGlobal.databus.selectedData.pop();
    if (GameGlobal.databus.slotCardsdData.includes(popItem)) {
      GameGlobal.databus.slotCardsdData.pop();
    } else {
      // 没有的时候要处理
    }

    GameGlobal.databus.cardsData.splice(popItem.index, 0, popItem);

    this.update();
  }
}
